import Vue from "vue";

Vue.directive("watermark", (el, binding) => {
  (function (str, container, id, font) {
    setTimeout(function () {
      var containerWidth = container.offsetWidth || "400"; // 获取父容器宽
      var containerHeight = container.offsetHeight || "100"; // 获取父容器高
      container.style.position = "relative"; // 设置布局为相对布局

      // 创建canvas元素(先制作一块背景图)
      const can = document.createElement("canvas");
      can.width = 300; // 设置每一块的宽度
      can.height = 120; // 高度
      const cans = can.getContext("2d"); // 获取canvas画布
      cans.rotate((-20 * Math.PI) / 270); // 逆时针旋转π/9
      cans.font = font || "16px PingFang-SC-Regular"; // 设置字体
      cans.fillStyle = "#666"; // 设置字体的颜色
      cans.textAlign = "left"; // 文本对齐方式
      cans.textBaseline = "Middle"; // 文本基线
      cans.fillText(str,  can.width / 20, (4 * can.height) / 5); // 绘制文字

      // 创建一个div元素
      const div = document.createElement("div");
      div.id = id; // 设置id
      div.style.pointerEvents = "none"; // 取消所有事件
      div.style.top = "0px";
      div.style.left = "40px";
      div.style.opacity = '0.15'
      div.style.position = "absolute";
      div.style.zIndex = "100000";
      div.style.width = containerWidth + "px";
      div.style.height = containerHeight + "px";
      div.style.overflow = "hidden";
      div.style.background =
        "url(" + can.toDataURL("image/png") + ") left top repeat";
      container.appendChild(div); // 追加到页面
    }, 300);
  })(binding.value.text, el, binding.value.id, binding.value.font);
});
